package com.hl.card.common.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class OssTool {

    private static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    private static String accessKeyId = "LTAICJo7h1mwb8eE";
    private static String accessKeySecret = "wiDePKZR2N3VXYd1wsMuGsqGphVmCn";
    private static String bucketName = "hlbibi";
    private static String downloadUri="https://hlbibi.oss-cn-shenzhen.aliyuncs.com";
    private static  String baseUri="usercenter/headimg/";

    private final static Logger logger = LoggerFactory.getLogger(OssTool.class);
    /**
     *
     * @param source 文件base64内容
     * @param fileName
     */
    public static void upload(String source,String fileName){
        OSS ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。
        ossClient.putObject(bucketName, baseUri+fileName, new ByteArrayInputStream(source.getBytes()));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void upload(byte[] source,String fileName){
        OSS ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。
        ossClient.putObject(bucketName, baseUri+fileName, new ByteArrayInputStream(source));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static  String download(String objectName){
        OSS ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, baseUri+objectName);
        InputStream content = ossObject.getObjectContent();
        StringBuilder sb=new StringBuilder();
        try{
            if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) break;
                    sb.append(line);
                }
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                content.close();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return sb.toString();
    }
    public static void delete(String objectName){
        OSS ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, baseUri+objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
//        double accuracy = 0.85;
        try {
            while (imageBytes.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
                    "", srcSize / 1024, imageBytes.length / 1024);
        } catch (Exception e) {
            logger.error("【图片压缩】msg=图片压缩失败!", e);
        }
        return imageBytes;
    }
    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小，单位kb
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
//            accuracy = 0.6;
            accuracy = 0.8;
        } else if (size < 3275) {
//            accuracy = 0.44;
            accuracy = 0.7;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }
}
